package com.byd.dms.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.reflect.TypeUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.lang.reflect.ParameterizedType;

public class FastDemo6 {
    
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class User<T> {
        private Integer age;
        private T t;
    }
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Attribute {
        private String attrName;
        private Object attrValue;
    }
    
    public static void main(String[] args) {
        String json = "{\"age\":18,\"t\":{\"attrName\":\"define\",\"attrValue\":123}}";
    }
    
    private static final String json = "{\"age\":18,\"t\":{\"attrName\":\"define\",\"attrValue\":123}}";
    
    
    @Test
    public void demo2() {
        
        ParameterizedTypeImpl parameterizedType = ParameterizedTypeImpl.make(User.class, new Class[]{Attribute.class}, null);
        User<Attribute> user = JSON.parseObject(json, parameterizedType);
        System.out.println("parameterizedType = " + parameterizedType);
        
        ParameterizedType type = TypeUtils.parameterize(User.class, Attribute.class);
        System.out.println("type = " + type);
        
        System.out.println(user);
    }
    
    @Test
    public void demo1( ) {
        User<Attribute> attributeUser = JSON.parseObject(json, new TypeReference<User<Attribute>>() {
        });   //   right: 但是写死了代码
        
        Attribute t = attributeUser.getT();
        System.out.println(t);
        
        Deserialization<Attribute> attributeDeserialization = new Deserialization<>(json);
        // 测试序列化是否成功
        System.out.println(attributeDeserialization.getUser().getT().getAttrValue()); // X 通用，但是泛型不行
        // error：java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.printerx.SFTest$Attribute
    }
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Deserialization<T> {
        private String json;
        
        public User<T> getUser() {
            return JSON.parseObject(json, new TypeReference<User<T>>() {
            });
        }
    }
}
